﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ChoWorkflowServer.Model;

namespace ChoWorkflowServer
{
    public static class ChoCalendarIntervalUtil
    {
        public static IEnumerable<DateTimeOffset?> ComputeRepeatFireDates(ChoTasksDataSet.CHO_TASK_SCHEDULESRow scheduleRow,
            DateTimeOffset nextFireDateTime)
        {
            yield return nextFireDateTime;

            if (scheduleRow == null)
                yield break;

            if (!scheduleRow.REPEAT_ENABLED)
                yield break;

            if (scheduleRow.IsREPEAT_INTERVALNull() || scheduleRow.IsREPEAT_INTERVAL_TYPENull())
                yield break;

            int repeatInterval = scheduleRow.REPEAT_INTERVAL;
            if (repeatInterval <= 0)
                yield break;

            DateTimeOffset endFireDateTime;

            if (scheduleRow.IsEND_TIMENull())
                endFireDateTime = new DateTimeOffset(nextFireDateTime.Date.EndOfDay(), nextFireDateTime.Offset);
            else
                endFireDateTime = new DateTimeOffset(new DateTime(nextFireDateTime.Date.Year, nextFireDateTime.Date.Month, nextFireDateTime.Date.Day, scheduleRow.END_TIME.Hour, scheduleRow.END_TIME.Minute, 
                    scheduleRow.END_TIME.Second), nextFireDateTime.Offset);

            ChoRepeatIntervalType repeatIntervalType = (ChoRepeatIntervalType)scheduleRow.REPEAT_INTERVAL_TYPE;
            if (repeatIntervalType == ChoRepeatIntervalType.Minutes)
            {
                while (nextFireDateTime < endFireDateTime)
                {
                    nextFireDateTime = nextFireDateTime.AddMinutes(repeatInterval);
                    yield return nextFireDateTime;
                }
            }
            else
            {
                while (nextFireDateTime < endFireDateTime)
                {
                    nextFireDateTime = nextFireDateTime.AddHours(repeatInterval);
                    yield return nextFireDateTime;
                }
            }
        }
    }
}
